using MediatR;
using Microsoft.AspNetCore.Mvc;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Controllers
{
    /// <summary>
    /// 库位信息读操作控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class StoragelocationController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<StoragelocationController> logger;

        /// <summary>
        /// 构造函数，注入MediatR和日志服务
        /// </summary>
        /// <param name="mediator">MediatR中介者</param>
        /// <param name="logger">日志服务</param>
        public StoragelocationController(IMediator mediator, ILogger<StoragelocationController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 分页查询库位信息（包含主管名称）
        /// </summary>
        /// <param name="queryDTO">查询条件数据传输对象</param>
        /// <returns>返回分页查询结果</returns>
        [HttpGet]
        public async Task<ApiResult<ApiPaging<List<StoragelocationInfoResultDTO>>>> QueryStoragelocation([FromQuery] StoragelocationQueryDTO queryDTO)
        {
            logger.LogInformation($"开始查询库位信息，页码：{queryDTO.PageIndex}，每页大小：{queryDTO.PageSize}");
            
            return await mediator.Send(new StoragelocationInfoQueryCommand
            {
                QueryDTO = queryDTO
            });
        }

        /// <summary>
        /// 根据ID查询库位信息（包含主管名称）
        /// </summary>
        /// <param name="storagelocationId">库位编号</param>
        /// <returns>返回库位信息</returns>
        [HttpGet]
        public async Task<ApiResult<StoragelocationInfoResultDTO>> GetStoragelocationById([FromQuery] int storagelocationId)
        {
            logger.LogInformation($"开始查询库位信息，库位编号：{storagelocationId}");
            
            return await mediator.Send(new StoragelocationInfoQueryCommand
            {
                QueryDTO = new StoragelocationQueryDTO { PageIndex = 1, PageSize = int.MaxValue }
            }).ContinueWith(task =>
            {
                if (task.Result.Code == ApiResultEnum.查询成功)
                {
                    var item = task.Result.Data.Data.FirstOrDefault(x => x.StoragelocationId == storagelocationId);
                    if (item != null)
                    {
                        return new ApiResult<StoragelocationInfoResultDTO>
                        {
                            Code = ApiResultEnum.查询成功,
                            Message = "查询库位信息成功",
                            Data = item
                        };
                    }
                }
                
                return new ApiResult<StoragelocationInfoResultDTO>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = "库位信息不存在",
                    Data = null
                };
            });
        }
    }
}

